package com.tang.campus_market.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tang.campus_market.dao.CommentDao;
import com.tang.campus_market.entity.Comment;
import com.tang.campus_market.service.CommentService;
import com.tang.campus_market.util.CommentData;
import com.tang.campus_market.util.CommentDiv;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentDao commentDao;

    public Comment selectById(int id) {
        Comment comment = commentDao.selectById(id);
        if (!"1".equals(comment.getState())) {
            return null;
        }
        return comment;
    }

    /**
     * @deprecated
     * 分页查询工具
     */
    public List<Comment> queryPaginationByColumn(String columnRealName, Object value, int pageId, int pageSize) {
        Page<Comment> page = new Page<>(pageId, pageSize);
        Wrapper<Comment> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq(columnRealName, value)
                .eq("state", 1);//待改进
        return commentDao.selectPage(page, entityWrapper);
    }


    /**
     * TODO:评论状态判断
     * TODO:1. 该评论已被隐藏 ,评论的字符串处理新建一个方法抽取一下，2.根评论下评论超过过多时，显示字符串（共x条评论）；3.分页多少页如何给前端？
     *
     * @param goodsId 商品id
     * @param pageId  商品评论页码
     * @param size    每页评论个数
     * @return CommentDiv列表，具体查看CommentDiv构造
     */
    @SuppressWarnings("All")
    public CommentData getHomeComments(Integer goodsId, int pageId, int size) {
        List<CommentDiv> commentDivList = new ArrayList<>();
        // ----------------分页查询--------------
        Page<Comment> page = new Page<>(pageId, size);
        Wrapper<Comment> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("goods_id", goodsId)
                .and("root_id is null")
                .eq("state", 1);//待改进
        List<Comment> rootCommentList = commentDao.selectPage(page, entityWrapper);
        Integer commentDivListCount= commentDao.selectCount(entityWrapper);

        // ----------------分页查询END--------------

        for (int i = 0; i < rootCommentList.size(); i++) {
            //获取评论的id
            CommentDiv commentDiv = new CommentDiv();
            Comment eachRootComment = rootCommentList.get(i);
            Integer eachRootCommentId = eachRootComment.getId();
            //分页查询子评论子评论的rootId即为评论的id
            //默认自动展开三条子评论
            //------------根评论下的子评论的分页查询-----------------
            Page<Comment> page1 = new Page<>(1, 3);
            Wrapper<Comment> entityWrapper1 = new EntityWrapper<>();
            entityWrapper1.eq("root_id", eachRootCommentId)
                    .eq("state", 1);//待改进
            List<Comment> subCommentList = commentDao.selectPage(page1, entityWrapper1);
            Integer subCommentListCount = commentDao.selectCount(entityWrapper1);
            //------------根评论下的子评论的分页查询-----------------
            commentDiv.setSubCommentList(subCommentList);
            commentDiv.setRootComment(eachRootComment);
            commentDiv.setSubCommentListCount(subCommentListCount);
            commentDivList.add(commentDiv);
        }
        CommentData commentData = new CommentData();
        commentData.setCommentDivList(commentDivList);
        commentData.setCommentDivListCount(commentDivListCount);
        return commentData;
    }

    /**
     * TODO:评论状态判断
     * 查询并返回一个CommentDiv
     *
     * @param rootId 根评论id，即评论商品的评论id
     * @param pageId 子评论页码，
     * @param size   每页个子评论的个数
     * @return 一个CommentDiv，具体查看CommentDiv的构造
     */
    public CommentDiv getSubComments(Integer rootId, int pageId, int size) {
        //------------子评论分页查询-----------------
        Page<Comment> page1 = new Page<>(pageId, size);
        Wrapper<Comment> entityWrapper1 = new EntityWrapper<>();
        entityWrapper1.eq("root_id", rootId)
                .eq("state", 1);//待改进
        List<Comment> subCommentList = commentDao.selectPage(page1, entityWrapper1);
        Integer subCommentListCount = commentDao.selectCount(entityWrapper1);
        //----------------子评论分页查询END--------------
        //根据子评论的rootId获取rootComment，子评论rootId即为rootComment的id；
        Comment rootComment = commentDao.selectById(rootId);
        //查询结果装载并返回
        CommentDiv commentDiv = new CommentDiv();
        commentDiv.setRootComment(rootComment);
        commentDiv.setSubCommentList(subCommentList);
        commentDiv.setSubCommentListCount(subCommentListCount);
        return commentDiv;
    }

    /**
     * TODO:评论状态判断
     * 插入一条评论
     *
     * @param comment 评论对象
     * @return 插入操作的结果，如果插入成功comment会被赋值成功后的对应表中属性。
     */
    public int insert(Comment comment) {
        //Comment包含goodsId，commentId，userId，content；
        //可以通过commentId查询rootId，如果直接指定rootId与commentId，非法请求的时候就会导致commentId与rootId不匹配
        //如果只指定rootId则无法判断回复的哪个评论。
        //如果commentId为空则表示评论的商品。此时rootId也为空
        //如果commentId不为空则指定rootId；

        //-----------置空非法参数------------------
        comment.setRootId(null);
        comment.setNickName(null);
        comment.setId(null);
        comment.setPicture(null);
        //-----------置空非法参数END------------------

        Integer commentId = comment.getCommentId();
        if (commentId != null) {


            //根评论的id即为子评论的rootId
            Comment fatherComment = commentDao.selectById(commentId);
            if (fatherComment == null) {
                return -1;
            }
            //评论的状态检查,TOOP：通过查询操作限制state
            if (!"1".equals(fatherComment.getState())) {
                return -1;
            }
            Integer rootId = fatherComment.getRootId();
            if (rootId == null) {
                rootId = fatherComment.getId();
            }
            comment.setRootId(rootId);
        }
        Date currentDate = new Date();
        //是否创建过此评论，如果没有则设置当前为创建时间
        comment.setCreateDate(currentDate);
        //设置当前时间为修改日期
        comment.setModifyDate(currentDate);
        comment.setThumbsUp(0);
        comment.setState("1");
        return commentDao.insert(comment);
    }

    /**
     * 用户删除评论。
     * 如果删除根评论，则删除根评论状态改为2-用户删除，其下子评论也改为2-用户删除
     * 如果删除子评论，则该子评论状态改为2-用户删除
     *
     * @param id 评论id
     * @return 评论删除条数
     */

    @Transactional
    public int deleteCommentByUser(Integer id) {
        int deleteResult = 0;
        Comment comment = commentDao.selectById(id);
        if (comment.getRootId() == null) {//是根评论
            Wrapper<Comment> wrapper = new EntityWrapper<>();
            wrapper.eq("root_id", id);
            deleteResult += commentDao.updateCommentStateByRootId(id, "2");
        }
        deleteResult += commentDao.updateCommentStateById(id, "2");
        return deleteResult;
    }

    /**
     * 管理员禁用评论
     * 如果禁用根评论，则根评论状态改为0-禁用，其下子评论也改为2-用户删除
     * 如果禁用子评论，则该子评论状态改为0-禁用
     *
     * @param id 评论id
     * @return 评论禁用的条数
     */
    @Transactional
    public int banComment(Integer id) {
        int deleteResult = 0;
        Comment comment = commentDao.selectById(id);
        if (comment.getRootId() == null) {
            Wrapper<Comment> wrapper = new EntityWrapper<>();
            wrapper.eq("root_id", id);
            deleteResult += commentDao.updateCommentStateByColumnName("root_id", id, "2");
        }
        deleteResult += commentDao.updateCommentStateByColumnName("id", id, "0");
        return deleteResult;
    }
//    public void getCommentsRecursion(List<Comment> resultList, Integer commentId, int count) {
//        //commentId - commentList - commentId - commentList - commentId
//        if (count == 0 || commentId == null) {
//            return;
//        }
//        List<Comment> commentList = queryPagination("commentId", commentId, 1, 3);
//        for (int i = 0; i < commentList.size(); i++) {
//            Comment comment = commentList.get(i);
//            commentId = comment.getCommentId();
//            //每次只能添加一个，为了判断count条数是否满足count全局共享
//            resultList.add(comment);
//            count--;
//            getCommentsRecursion(resultList, commentId, count);
//            if (count == 0) {
//                return;
//            }
//        }
//        return;
//
//    }


}
